<template>
  <div class="wrap">
    <div v-for="(item,index) in list" :key="index" class="cell u-flex u-row-between" @click="change(item,index)">
      <span>{{item.lang_name}}</span>
      <u-icon name="checkbox-mark" color="#2979ff" size="28" v-if="item.is_default==1"></u-icon>
    </div>
    <u-toast ref="uToast" />
  </div>
</template>

<script>
export default {
  data(){
    return{
      list:[]
    }
  },
  onLoad() {
     this.getLangList()
    uni.setNavigationBarTitle({
      title:'多语言'
    });
   
  },
  methods:{
    change(e,index){
      this.list.forEach(res=>res.is_default=0)
      e.is_default =1
      if(e.lang_code.includes('-')){
        e.lang_code =  e.lang_code.replace('-','')
      }
      this.$i18n.locale = e.lang_code;
      console.log("-> this.$i18n.locale", this.$i18n.locale);
     
      uni.setStorageSync('langType',e.lang_code)
      uni.setStorageSync('langId',e.id)
      uni.$emit('changeLang',{type:e.lang_code})
      this.getLangKeyValue(e)
    
    },
    getLangList(){
      this.$http.getLangList().then(res=>{
          let list = res.data
        let langId = uni.getStorageSync('langId')
        if(langId){
          let setIndex=  list.findIndex(res=>res.id===langId)
          console.log("-> setIndex", setIndex);
          list.forEach(res=>res.is_default=0)
          list[setIndex].is_default=1
        }
       
          this.list  = list
      })
    },
  getLangKeyValue(item){
      this.$http.getLangKeyValue({lang_id:item.id}).then(res=>{
          if(res.status===200){
               this.$hideLoading()
            this.$refs.uToast.show({
              title: '下载成功',
              type: 'success',
              duration:1000
            })
            const type = item.lang_code
            // let data = {};
            //    data[type] = res.data[0]
             uni.setStorageSync(type, res.data[0])
         
          }else{
            this.$toast('获取语言包失败')
          }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  background-color: #fff;
}
.cell{
  padding: 25upx;
  font-size: 32upx;
  border-bottom: 1upx solid #f5f5f5;
}
</style>
